<!-- //根据浏览器的本地储存动态填充个人页面 -->
 <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心——校园技能互助平台</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="js/user-manager.js"></script>
    <link rel="stylesheet" href="style/profile.css">
    <link rel="stylesheet" href="style/loading.css">
</head>
<body>
    <div id="app">
        <profile-page></profile-page>
    </div>

<div class="global-loader" id="globalLoader">
    <div class="loader-ring"></div>
    <p class="loading-text">加载中...</p>
    <div class="progress-bar">
      <div class="progress" id="loaderProgress"></div>
    </div>
  </div>

    <script>
        Vue.component('profile-page', {
            template: `
                <div>
                    <!-- 导航栏 -->
                    <nav class="navbar">
                        <div class="nav-content">
                            <div class="logo">personal profile</div>
                            <div class="nav-links">
                                <a href="forum.html">论坛首页</a>
                                <a href="skills.html">我要发贴</a>
                                <a href="messages.html">消息中心</a>
                                <span>欢迎，{{ currentUser.username }}</span>
                            </div>
                        </div>
                    </nav>

                    <!-- 个人中心内容 -->
                    <div class="profile-container">
                        <!-- 用户信息头部 -->
                        <div class="profile-header">
                            <div class="avatar">
                                {{ currentUser.username.charAt(0).toUpperCase() }}
                            </div>
                            <div class="user-info">
                                <h1>{{ currentUser.username }}</h1>
                                <p>学号：{{ currentUser.username }}</p>
                                <p>邮箱：{{ userProfile.email }}</p>
                                <p>注册时间：{{ formatDate(userProfile.registerTime) }}</p>
                                <button class="edit-btn" @click="toggleEdit">{{ isEditing ? '取消编辑' : '编辑资料' }}</button>
                                <button class="logout-btn" @click="logout">退出登录</button>
                            </div>
                        </div>

                        <!-- 数据统计 -->
                        <div class="stats">
                            <div class="stat-card">
                                <div class="stat-number">{{ userStats.posts }}</div>
                                <div class="stat-label">发布的帖子</div>
                            </div>
                            <div class="stat-card">
                                <div class="stat-number">{{ userStats.skills }}</div>
                                <div class="stat-label">your skill is ……</div>
                            </div>
                            <div class="stat-card">
                                <div class="stat-number">{{ userStats.helps }}</div>
                                <div class="stat-label">帮助次数</div>
                            </div>
                            <div class="stat-card">
                                <div class="stat-number">{{ userStats.points }}</div>
                                <div class="stat-label">积分</div>
                            </div>
                        </div>

                        <!-- 主要内容区域 -->
                        <div class="profile-sections">
                            <!-- 左侧：个人信息编辑 -->
                            <div class="section-card">
                                <h2 class="section-title">self-information</h2>
                                <div v-if="!isEditing">
                                    <p><strong>name：</strong>{{ userProfile.nickname || '未设置' }}</p>
                                    <p><strong>major：</strong>{{ userProfile.major || '未设置' }}</p>
                                    <p><strong>grade：</strong>{{ userProfile.grade || '未设置' }}</p>
                                    <p><strong>self-introduction：</strong>{{ userProfile.bio || '这个人很懒，什么都没有写～' }}</p>
                                </div>
                                <div v-else>
                                    <input v-model="editProfile.nickname" placeholder="name" class="input-field">
                                    <input v-model="editProfile.major" placeholder="major" class="input-field">
                                    <input v-model="editProfile.grade" placeholder="grade" class="input-field">
                                    <textarea v-model="editProfile.bio" placeholder="self-introduction" class="input-field" rows="4"></textarea>
                                    <button class="save-btn" @click="saveProfile">save changes</button>
                                </div>
                            </div>

                            <!-- 右侧：技能标签 -->
                            <div class="section-card">
                                <h2 class="section-title">my skills</h2>
                                <div v-if="!isEditingSkills">
                                    <div v-if="userProfile.skills && userProfile.skills.length > 0">
                                        <span v-for="skill in userProfile.skills" :key="skill" class="skill-tag">
                                            {{ skill }}
                                        </span>
                                    </div>
                                    <p v-else class="no-skills">还没有添加任何技能</p>
                                    <button class="edit-btn" @click="toggleEditSkills">
                                        {{ isEditingSkills ? '取消编辑' : '编辑技能' }}
                                    </button>
                                </div>
                                <div v-else>
                                    <div class="skill-input-container">
                                        <input v-model="newSkill" placeholder="输入技能" 
                                               class="skill-input" @keyup.enter="addSkill">
                                        <button class="add-skill-btn" @click="addSkill">add</button>
                                    </div>
                                    <div>
                                        <span v-for="(skill, index) in editSkills" :key="index" class="skill-tag">
                                            {{ skill }}
                                            <span @click="removeSkill(index)" class="skill-remove">×</span>
                                        </span>
                                    </div>
                                    <button class="save-btn" @click="saveSkills" style="margin-top: 1rem;">保存技能</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `,
            data() {
                return {
                    currentUser: {},
                    userProfile: {},
                    userStats: {
                        posts: 0,
                        skills: 0,
                        helps: 0,
                        points: 0
                    },
                    isEditing: false,
                    isEditingSkills: false,
                    editProfile: {},
                    editSkills: [],
                    newSkill: ''
                };
            },
            methods: {
                loadUserData() {
                    // 获取当前登录用户
                    const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
                    if (!currentUser.username) {
                        alert('请先登录');
                        window.location.href = 'login.html';
                        return;
                    }
                    this.currentUser = currentUser;

                    // 获取用户详细信息
                    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
                    const userData = registeredUsers.find(user => user.username === currentUser.username);
                    
                    if (userData) {
                        this.userProfile = {
                            email: userData.email,
                            registerTime: userData.registerTime,
                            nickname: userData.nickname || '',
                            major: userData.major || '',
                            grade: userData.grade || '',
                            bio: userData.bio || '',
                            skills: userData.skills || []
                        };
                    }

                    // 获取用户统计信息
                    this.loadUserStats();
                },

                loadUserStats() {
                    // 从localStorage加载用户统计数据
                    const userStats = JSON.parse(localStorage.getItem('userStats') || '{}');
                    this.userStats = userStats[this.currentUser.username] || {
                        posts: 0,
                        skills: this.userProfile.skills ? this.userProfile.skills.length : 0,
                        helps: 0,
                        points: 100
                    };
                },

                toggleEdit() {
                    this.isEditing = !this.isEditing;
                    if (this.isEditing) {
                        this.editProfile = { ...this.userProfile };
                    }
                },

                toggleEditSkills() {
                    this.isEditingSkills = !this.isEditingSkills;
                    if (this.isEditingSkills) {
                        this.editSkills = [...(this.userProfile.skills || [])];
                    }
                },

                saveProfile() {
                    // 更新用户资料
                    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
                    const userIndex = registeredUsers.findIndex(user => user.username === this.currentUser.username);
                    
                    if (userIndex !== -1) {
                        registeredUsers[userIndex] = {
                            ...registeredUsers[userIndex],
                            ...this.editProfile
                        };
                        localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers));
                        
                        this.userProfile = { ...this.editProfile };
                        this.isEditing = false;
                        alert('资料更新成功！');
                    }
                },

                addSkill() {
                    if (this.newSkill.trim() && !this.editSkills.includes(this.newSkill.trim())) {
                        this.editSkills.push(this.newSkill.trim());
                        this.newSkill = '';
                    }
                },

                removeSkill(index) {
                    this.editSkills.splice(index, 1);
                },

                saveSkills() {
                    this.userProfile.skills = [...this.editSkills];
                    
                    // 更新到localStorage
                    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
                    const userIndex = registeredUsers.findIndex(user => user.username === this.currentUser.username);
                    
                    if (userIndex !== -1) {
                        registeredUsers[userIndex].skills = this.editSkills;
                        localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers));
                        
                        this.isEditingSkills = false;
                        this.userStats.skills = this.editSkills.length;
                        this.saveUserStats();
                        alert('技能更新成功！');
                    }
                },

                saveUserStats() {
                    const userStats = JSON.parse(localStorage.getItem('userStats') || '{}');
                    userStats[this.currentUser.username] = this.userStats;
                    localStorage.setItem('userStats', JSON.stringify(userStats));
                },

                formatDate(dateString) {
                    if (!dateString) return '未知';
                    return new Date(dateString).toLocaleDateString('zh-CN');
                },

                logout() {
                    localStorage.removeItem('currentUser');
                    alert('已退出登录');
                    window.location.href = 'login.html';
                }
            },
            mounted() {
                this.loadUserData();
            }
        });

        new Vue({
            el: '#app'
        });

        // 获取加载画面元素
    const loader = document.getElementById('globalLoader');
    const progressBar = document.getElementById('loaderProgress');
    let progressTimer = null;

    // 显示加载画面并模拟进度
    function showLoader() {
      loader.classList.add('show'); // 显示加载画面
      progressBar.style.width = '0%'; // 重置进度条
      
      // 模拟进度增长（每次+5%~10%）
      let progress = 0;
      clearInterval(progressTimer);
      progressTimer = setInterval(() => {
        progress += Math.random() * 5 + 5; // 5%-10% 随机增长
        if (progress >= 90) { // 最多到90%，留10%等页面加载完成
          progress = 90;
          clearInterval(progressTimer);
        }
        progressBar.style.width = progress + '%';
      }, 200);
    }

    // 隐藏加载画面（补全进度）
    function hideLoader() {
      progressBar.style.width = '100%'; // 进度条拉满
      setTimeout(() => {
        loader.classList.remove('show'); // 隐藏加载画面
        clearInterval(progressTimer);
      }, 300); // 等待进度条动画完成
    }

    // 示例1：页面加载时显示加载画面（模拟初始加载）
    window.addEventListener('load', () => {
      // 页面加载完成后隐藏
      hideLoader();
    });
    // 页面开始加载时显示
    showLoader();

    // 示例2：点击链接跳转时显示加载画面
    const links = document.querySelectorAll('.nav-link');
    links.forEach(link => {
      link.addEventListener('click', (e) => {
        // 阻止默认跳转，先显示加载画面
        e.preventDefault();
        const targetUrl = link.href;
        
        showLoader();
        // 延迟300ms跳转（让用户看到加载动画）
        setTimeout(() => {
          window.location.href = targetUrl;
        }, 900);
      });
    });
    </script>
    <!-- <script src="js/nav.js"></script>
     <script src="js/login.js"></script>
    <script src="js/modal.js"></script>
    <script src="js/navToggle.js"></script>
    <script src="js/headNavToggle.js"></script>
    <script src="js/goToHexo.js"></script> -->
</body>
</html>